<template>
  <div class="app-container">
    <div style="font-size:15px; margin-bottom: 40px;">
      <span>非自动出飞车辆登记</span>
      <el-divider></el-divider> 
      <span class="tips">
          请输入相应的公司信息和司机信息  
      </span>   
    </div> 
    <el-form v-loading="loading" ref="form" :model="form" label-width="120px">
      <el-row :gutter="30">
        <!-- 身份证信息 --> 
        <el-col :span="8">
              <el-form-item label="PCC卡号">
                <el-input v-model="form.pccId" disabled></el-input>
              </el-form-item>
        </el-col> 
        <el-col :span="16"> 
          <!-- 运通卡信息 -->
            <el-form-item label="车牌" class="labelRed">
              <span style="width: 50px; float: left; margin-left: 10px;">
                <el-input v-model="form.vehicleColor" disabled></el-input>
              </span> 
              <span style="width: 80px; float: left; margin-left: 10px;">
                <el-input v-model="form.vehiclePy"></el-input> 
              </span>  
              <span style="width: 150px; float: left; margin-left: 10px;"> 
                 <el-input v-model="form.vehicleKey"></el-input>
              </span>
              <span class="vehicleColor"> 
                {{form.vehicleSuf}}
              </span>
            </el-form-item>
            
        </el-col>
      </el-row>

      <el-row :gutter="30">
        <!-- 公司名称 --> 
        <el-col :span="10">
              <el-form-item label="公司名称" >
                <el-input v-model="form.companyName" disabled></el-input>
              </el-form-item>
        </el-col>  
      </el-row>

      <el-row :gutter="30">
        <!-- 司机姓名 -->
        <el-col :span="8">
              <el-form-item label="司机姓名" class="labelRed">
                <el-input v-model="form.idName"></el-input>
              </el-form-item>
        </el-col> 
        <el-col :span="8">
          <!-- 运通卡信息 -->
            <el-form-item label="司机联系方式" class="labelRed">
              <el-input v-model="form.manTel" ></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="8">
          <!-- 运通卡信息 -->
            <el-form-item label="身份证号码"  class="labelRed">
              <el-input v-model="form.driverCardId" ></el-input>
            </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="30">
        <!-- 身份证信息 -->
        <el-col :span="16">
              <el-form-item label="原因">
                <!-- <el-input v-model="form.reason" disabled></el-input> -->
                <el-select v-model="form.reason" style="width: 100%">
                  <el-option
                    v-for="item in reasons"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"> 
                  </el-option>
                </el-select>
              </el-form-item>
        </el-col> 
        
        <el-col :span="8">
          <!-- 运通卡信息 -->
            <!--<el-form-item label="SSD回执号"  class="labelRed">
               <el-input v-model="form.returnReceiptId" disabled></el-input> 
            </el-form-item>-->
        </el-col>
      </el-row>

      <el-row :gutter="30">
        <!-- 身份证信息 -->
        <el-col :span="8">
              <el-form-item label="设备类型">
                <el-select v-model="form.idDevice" disabled>
                  <el-option
                    v-for="item in idDevices"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"> 
                  </el-option>
                </el-select>
              </el-form-item>
        </el-col> 
        <el-col :span="16">
          <!-- 运通卡信息 -->
            <el-form-item label="操作方式">
              <el-select v-model="form.operatingMode" disabled>
                  <el-option
                    v-for="item in operats"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"> 
                  </el-option>
                </el-select>
            </el-form-item>
        </el-col>
      </el-row>
 
      <el-form-item style="text-align: center; margin-top: 25px;">
        <el-button @click="isReadIcCard = true">刷PCC卡</el-button>
        <el-button @click="isReadIdCard = true">刷身份证</el-button> 
        <el-button @click="reset">重置</el-button>  
        <el-button @click="insertIDTractor">确定</el-button>
        <!-- <el-button>取消</el-button> -->
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { ipcRenderer } from 'electron'
import axios from 'axios'
import {
  showSuccessMsg,
  showErrorMsg,
  showWarningMsg,
  showInfoMsg,
  showNotify,
  debugLog,
  log,
} from '@/utils/message'
import { getNetworkIp } from '@/utils/http'
import { isBlank, checkCardId } from '@/utils/validate'
export default {
  components: { Tinymce },
  data() {
    return {
      checkPcIC: 'OSD-Check-Pcc-Card',
      saveIC: 'OSD-Save',
      sendMqttMsgSeq: 0,
      appConfigData: null,
      loading: false,
      isReadIdCard: false,
      isReadIcCard: false,
      hasPccCard: false,
      readIdCardThread: null,
      readIcCardThread: null, 
      idDevices:[{
        value: '1',
        label: '一二代一体机'
      }, {
        value: '2',
        label: '二代证读卡器'
      }],
      operats:[{
        value: '1',
        label: '二代身份证读卡'
      }, {
        value: '2',
        label: '一代身份证扫描'
      }, {
        value: '3',
        label: '二代身份证扫描'
      }],
      reasons:[{
        value: '无PCC卡',
        label: '无PCC卡'
      }, {
        value: 'PCC卡已坏',
        label: 'PCC卡已坏'
      }, {
        value: '无效身份证',
        label: '无效身份证'
      }, {
        value: '使用第一代身份证',
        label: '使用第一代身份证'
      }, {
        value: '使用港澳身份证',
        label: '使用港澳身份证'
      }, {
        value: '使用驾驶证',
        label: '使用驾驶证'
      }, {
        value: '使用从业资格证',
        label: '使用从业资格证'
      }, {
        value: '无任何证件',
        label: '无任何证件'
      }, {
        value: '其他',
        label: '其他'
      }],
      form: {
        tcCode: '',
        pccId: '',
        companyName: '',
        returnReceiptId: '',
        //  "无PCC卡", "PCC卡已坏", "无效身份证", "使用第一代身份证", "使用港澳身份证",
				// "使用驾驶证", "使用从业资格证", "无任何证件", "其他" 
        reason: '',
        idDevice: '1',
        operatingMode: '1',
        idName: '',
        manTel: '',
        driverCardId: '',
        // "蓝", "黑", "绿", "红", "黄", "白"
        vehicleColor: '黄',
        vehiclePy: '',
        vehicleKey: '',
        // "", "港", "澳" 
        vehicleSuf: ''
      },
    }
  },
  created() {
    // 加载MQTT
    setTimeout(() => {
      this.startMqttConnect()
    }, 2000)

    /**
     * TODO 这里需要一个handle 处理各种异常信息提示 和服务器返回值
     *
     */
    setTimeout(() => {
      this.initReadThread()
    },  5000);
  },
  methods: {
    /**
     * checkPccCard
     */
    checkPccCard(pccId){
      // pcc
      let message = {
        dt: {
          nGenFullTractorNo: '',
          ip: getNetworkIp(),
          cardId: pccId,
        },
        ic: this.checkPcIC,
        sn: this.appConfigData.deviceSerialNo ,
        id: this.sendMqttMsgSeq,
        en: false
      }
      this.sendMqttMessage("api/ssd/checkPccCard", message)
    },
    /**
     * 新增
     */
    insertIDTractor() {
      // 校验参数
      if (!this.validateForm()){
        return false;
      }

      const qd = {
        idCard: this.form.driverCardId,
        manTel: this.form.manTel,
        idName: this.form.idName,
        tidNgenColor: this.form.tidNgenColor,
        tidNgenPy: this.form.tidNgenPy,
        tidNgenKey: this.form.tidNgenKey,
        tidNgenSuf: this.form.tidNgenSuf,
        tcCode: this.form.tcCode,
        companyName: this.form.companyName,
        ip: getNetworkIp(),
        reason: this.form.reason,
        returnReceiptId: this.form.returnReceiptId
      }

      let message = {
        dt: qd,
        ic: this.saveIC,
        sn: this.appConfigData.deviceSerialNo ,
        id: this.sendMqttMsgSeq,
        en: false
      }
      this.sendMqttMessage('api/ssd/register', message)    
    },
    // 成功的回掉
    saveCallback(rs) {
      showSuccessMsg('操作成功，飞仔已打印')
      this.reset()
    },
    // 重置
    reset(){
      this.form = {
        tcCode: '',
        pccId: '',
        returnReceiptId: '',
        reason: '',
        idDevice: '1',
        operatingMode: '1',
        idName: '',
        manTel: '',
        driverCardId: '',
        vehicleColor: '黄',
        vehiclePy: '',
        vehicleKey: '',
        vehicleSuf: ''
      }

      // 暂停读卡
      this.isReadIdCard = false
      this.isReadIcCard = false
      this.hasPccCard = false
    },
    // 校验表单是否可以提交
    validateForm (){
      if (isBlank(this.form.vehiclePy)){
        showWarningMsg("请输入车牌省份")
        return false
      }

      if (isBlank(this.form.vehicleKey)){
        showWarningMsg("请输入车牌号码")
        return false
      }

      const driveName = this.form.idName
      if (isBlank(driveName) || driveName.length < 2 || driveName.length > 6){
        showWarningMsg("司机姓名应该在2-6个字")
        return false
      } 

      // 不能有数字
      let reg = /\d/
      if (reg.test(driveName)){
        showWarningMsg("司机姓名不能有数字")
        return false
      }

      // 司机身份证号
      const driverCardId = this.form.driverCardId
      if (isBlank(driverCardId)) {
        showWarningMsg("请输入有效的身份证号")
        return false
      }

      if (driverCardId.length === 18){
        if (!checkCardId(driverCardId)){
          showWarningMsg("请输入有效的身份证号")
          return false  
        }
      } else if (driverCardId.length !== 15){
          showWarningMsg("请输入有效的身份证号")
          return false  
      } else {
        if (!/^\d+$/.test(driverCardId)){
          //15位的必须全部是数字
          showWarningMsg("请输入有效的身份证号")
          return false     
        }
      }

      if (isBlank(this.form.manTel)) {
        showWarningMsg("请输入司机联系方式")
        return false
      }

      // driverNameField
      return true
    },
    /**
     * 写PCC的回调
     */
    writePccInfo(dt) {
      this.form.driverCardId = dt.idNo
      this.form.returnReceiptId = dt.returnReceiptId
      this.form.idName = dt.idName
      this.form.manTel = dt.manTel
      this.form.companyName = dt.companyName
    },
    //清空暂停线程
    stopReadThread() {
      //停止读卡线程
      this.stopReadIdCardThread()
      this.stopReadIcCardThread()
      // this.resetShowMessage()
      debugLog('关闭读卡服务')
      //重启服务
      /*     setTimeout(() => {
        this.loadCardDll()
      }, 2000) */
    }, 
    // 初始化加载dll
    loadCardDll() {
      console.log('loadCardDll')
      ipcRenderer.send('load-card-dll-thread')
      ipcRenderer.on('load-card-dll-thread-reply', (event, res) => {
        log('load-card-dll-thread-reply')
        debugLog(res)
        this.registerReadListener()
        this.startReadIdCardThread()
        this.startReadIcCardThread()

        debugLog('读卡服务启动成功')
      })
    },
    // 重置
    resetShowMessage() {
      log('=== resetShowMessage ===')
      this.showMessage = {
        msg: '请刷卡......',
        success: false,
        type: 'success',
      }
    },
     // 开启读ID卡线程
    startReadIdCardThread() {
      this.stopReadIdCardThread()
      this.readIdCardThread = window.setInterval(() => {
        if (this.isReadIdCard) {
          // TODO 这里需要根据平台的属性type来判断读一二代身份证， 需要确认
          ipcRenderer.send('read-id-card')
        } 
      }, 1000)
    },
    //关闭读ID卡线程
    stopReadIdCardThread() {
      if (this.readIdCardThread) {
        window.clearInterval(this.readIdCardThread)
      }
      return true
    },
    // 开启读IC卡线程
    startReadIcCardThread() {
      this.stopReadIcCardThread()
      debugLog('开始读 read-ic-card', '读卡信息')
      this.readIcCardThread = window.setInterval(() => {
        if (this.isReadIcCard) { 
          ipcRenderer.send('read-ic-card')
        }
      }, 1000)
    },
    //关闭读IC卡线程
    stopReadIcCardThread() {
      if (this.readIcCardThread) {
        window.clearInterval(this.readIcCardThread)
      }
      return true
    },
    initReadThread() {
      this.stopReadThread()
      debugLog('初始化读卡服务', '读卡信息')
      //重启服务
      setTimeout(() => {
        this.loadCardDll()
      }, 2000)
    },
    readAppConfig() {
      ipcRenderer.send('read-app-config', '读取本地文件的配置文件')
      ipcRenderer.on('read-app-config-reply', (event, res) => {
        log(res)
        this.appConfigData = JSON.parse(res.data)
        this.startMqttConnect()
      })
    },
    // 注册ID和IC卡消息监听器
    registerReadListener() {
      // 注册ID卡消息监听器
      ipcRenderer.on('read-id-card-reply', (event, res) => {
        // 返回读卡接口 -999 返回0能读取到信息  返回 2代表设备链接，但是找不到卡   返回1代表设备没有连接 因为有中文所以要转码  111
        if (this.isReadIdCard) {
          log('====read-id-card-reply====')
          log(res)
          let msgInfo = JSON.stringify(res)
          if (res.readCode === 0) {
            // 读卡成功
            debugLog('身份证读取成功', 'success')
            this.form.name = res.name
            this.form.idNo = res.idNo
            showSuccessMsg('身份证读取成功', 'success')
            //暂停读取ID卡线程
            window.setTimeout(() => {
              this.pauseReadIdCard(res.idNo, res.name)
            }, 1000)
            msgInfo += '====读卡成功'
          } else if (res.readCode === 2) {
            // this.showMsg('身份证无效', 'error')
            msgInfo += '====身份证无效'
          } else {
            log('身份证设备连接错误', 'warning')
            msgInfo += '====身份证设备连接错误'
            // this.showMsg('身份证设备连接错误', 'warning')
          }
          debugLog(msgInfo, '读卡信息')
        }
      })
      // 注册IC卡消息监听器
      ipcRenderer.on('read-ic-card-reply', (event, res) => {
        log('====read-ic-card-reply====')
        let msgInfo = JSON.stringify(res)
        log(msgInfo)
        if (res.readCode == 0) {
          this.form.pccId = res.cardNo
          this.form.tcCode = res.permitNo
          showSuccessMsg('PCC卡读取成功', 'success')
          window.setTimeout(() => {
            // 执行CheckPcc的操作， 以及关闭读卡线程
            this.pauseReadIcCard(res.cardNo, res.permitNo)
          }, 1000)

          log('====PCC卡读取成功')
        } else if (res.readCode === 2) {
          log('PPC无效', 'error')
        } else {
          log('PC卡设备端口连接错误', 'warning')
        }
      })
    },
    // 读卡成功执行的方法， 暂停读卡线程
    pauseReadIdCard() {
      // if (this.isReadIdCard){
      //   this.showMsg('服务器正在验证卡信息', 'info')
      //   this.sendMqttMessage()  
      //   this.checkPccCard(cardNo)
      // }
      this.isReadIdCard = false  
    },
    // 读卡成功执行的方法， 暂停读卡线程
    pauseReadIcCard(cardNo, permitNo) {
      if (this.isReadIcCard){
        this.showMsg('服务器正在验证卡信息', 'info')
        // this.sendMqttMessage()  
        this.checkPccCard(cardNo)
      }
      this.hasPccCard = true
      this.isReadIcCard = false
    },
    // =====start===MQTT=====
    deviceAuthenticate(queryObject) {
      log(queryObject)
      debugLog(queryObject.eipUr)
      axios
        .post(queryObject.eipUrl + '/api/deviceAuthenticate', queryObject, {
          timeout: 3000,
        })
        .then((res) => {
          // var resObj = JSON.parse(res)
          var ret = res.data 
          log(ret, 'deviceAuthenticate') 
          if (ret.result && ret.result === 'success') {
            log('===设备注册成功===')
            debugLog(ret, '设备注册')
            this.appConfigData.sessionId = ret.data.sessionId
            this.appConfigData.serviceInstanceIpAddress =
              ret.data.serviceInstanceIpAddress
            this.appConfigData.serviceInstanceMqttPort =
              ret.data.serviceInstanceMqttPort
            this.connectMqtt(this.appConfigData)
          } else {
            showErrorMsg(res)
          }
        })
        .catch((error) => {
          showErrorMsg(error)
          // @TODO 发布生成注释掉这行代码
          this.loading = false
        })
    },
    connectMqtt(mqttObject) {
      log('startMqttConnect')
      debugLog(mqttObject, 'MQTT连接信息')
      ipcRenderer.send('start-mqtt-connect', mqttObject)

      ipcRenderer.on('start-mqtt-connect-reply', (event, res) => {
        log('====start-mqtt-connect-reply====')
        debugLog(res, 'MQTT链接结果')

        // 没注册成功前， 不可以扫描PCC， 因为扫描到PCC需要通过MQTT做请求
        if ( 1 == 1){
          this.loading = false
        }
      })
      //注册业务返回监听器
      ipcRenderer.on('send-mqtt-client-message-reply', (event, res) => {
        log('===send-mqtt-client-message-reply===')
        debugLog(res)
        this.loading = false
        this.handleMqttMessage(res)
      })

      ipcRenderer.on('mqtt-server-message-topic', (event, res) => {
        log('===mqtt-server-message-topic===')
        log(res)
      })
    },
    // 发送MQTT消息
    sendMqttMessage(url, message) {
      this.sendMqttMsgSeq += 1
      debugLog(message, '请求MQTT信息')
      this.loading = true
      ipcRenderer.send('send-mqtt-client-message', url, message)
    },
    showMsg(msg, type) {
      // this.showMessage.msg = msg
      // this.showMessage.type = type
      showInfoMsg(msg)
    },
    // MQTT后端业务返回消息处理方法
    handleMqttMessage(mqttMessage) {
      //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":1,"dt":["192764","zxc","","y|GD|BW8337|",""]}
      if (mqttMessage) {
        var messageObject = JSON.parse(mqttMessage)
        debugLog(messageObject, '回传信息')
        if (messageObject.rc && messageObject.rc == 1) {
          // this.showMsg('刷卡操作成功', 'success')
          if (messageObject.ic === this.checkPcIC){
            this.writePccInfo(messageObject.dt)
          }
          if (messageObject.ic === this.saveIC){
            this.saveCallback(messageObject.dt)
          }
        } else if (messageObject.rc) {
          //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":26,"rm":"未知的读卡器错误"}
          this.showMsg(messageObject.rm, 'warning')
        } else {
          this.showMsg('未知错误，请联系管理员。', 'warning')
        }
      }
    },
    // 关闭 MQTT服务器
    closeMqttConnect() {
      log('closeMqttConnect')
      ipcRenderer.send('close-mqtt-connect')

      ipcRenderer.on('close-mqtt-connect-reply', (event, res) => {
        log('close-mqtt-connect-reply')
        log(res)
      })
    },
    // 启动 MQTT服务器连接
    startMqttConnect() {
      this.loading = true
      this.closeMqttConnect()
      if (!this.appConfigData) { 
        this.readAppConfig()
      } 

      if (this.appConfigData) {
        setTimeout(() => {
          log('========appConfigData========')
          log(this.appConfigData)
          this.deviceAuthenticate(this.appConfigData)
          // var appConfigInfo = JSON.parse(this.appConfigDat)
          //验证读取本地配置文件  每次都
          // this.connectMqtt(this.appConfigData)
        }, 2000)
      }
    },
    onSubmit() {
      console.log(this.form)
      this.$message('submit!')
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning',
      })
    },
  },
}
</script>

<style scoped>
.line {
  text-align: center; 
}

.app-container{ 
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-size: 12px;
} 
 
.vehicleColor{
  display: block;
  background-color: #DCDFE6;
  padding-top: 5px;
  width: 50px; 
  height: 40px; 
  opacity: 0.6;
  line-height: 30px;
  border-radius: 3px;
  margin-left: 10px;
  float: left;
  text-align: center;
}

.labelRed >>> .el-form-item__label {
  color: red;
}
</style>
